package com.example.mplayer.viewmodels

import android.app.Application
import android.util.Log
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.viewModelScope
import com.example.mplayer.data.AppDatabase
import com.example.mplayer.data.ChapterWithVideos
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch

class CourseDetailViewModel(application: Application) : AndroidViewModel(application) {
    private val courseDao = AppDatabase.getDatabase(application).courseDao()

    private val _currentChapters = MutableStateFlow<List<ChapterWithVideos>>(emptyList())
    val currentChapters: StateFlow<List<ChapterWithVideos>> = _currentChapters.asStateFlow()

    private val _navigationStack = MutableStateFlow<List<String>>(listOf("root"))
    val navigationStack: StateFlow<List<String>> = _navigationStack.asStateFlow()

    private val _courseTitle = MutableStateFlow("")
    val courseTitle: StateFlow<String> = _courseTitle.asStateFlow()

    private var currentCourseId: String? = null

    fun loadInitialChapters(courseId: String) {
        currentCourseId = courseId
        viewModelScope.launch {
            Log.d("CourseDetail", "Loading initial chapters for course: $courseId")
            val course = courseDao.getCourseById(courseId)
            _courseTitle.value = course?.title ?: ""
            val rootChapters = courseDao.getRootChapters(courseId)
            Log.d("CourseDetail", "Loaded ${rootChapters.size} root chapters")
            _currentChapters.value = rootChapters
            _navigationStack.value = listOf("root")
        }
    }

    fun loadChapters(chapterId: String?) {
        viewModelScope.launch {
            Log.d("CourseDetail", "Loading chapters for parent: $chapterId")
            val chapters = if (chapterId == null) {
                currentCourseId?.let { courseDao.getRootChapters(it) } ?: emptyList()
            } else {
                courseDao.getSubChapters(chapterId)
            }
            Log.d("CourseDetail", "Loaded ${chapters.size} chapters")
            _currentChapters.value = chapters
            if (chapterId != null) {
                _navigationStack.value = _navigationStack.value + chapterId
            }
        }
    }

    fun navigateBack() {
        if (_navigationStack.value.size > 1) {
            val newStack = _navigationStack.value.dropLast(1)
            _navigationStack.value = newStack
            val parentChapterId = newStack.lastOrNull().takeIf { it != "root" }
            loadChapters(parentChapterId)
        }
    }
}